package org.vacoor.ticket.handler.impl.option;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.vacoor.ticket.Constant;
import org.vacoor.ticket.bean.option.Train;
import org.vacoor.ticket.handler.ResultHandler;
import org.vacoor.ticket.util.ParseUtil;

/**
 * 封装查询的所有经过列车信息
 * 该功能可以没有
 * @author vacoor
 *
 */
public class TrainResultHandler implements ResultHandler<List<Train>>{

	@Override
	public List<Train> handler(byte[] content) {
		String result;
		try {
			result = new String(content,Constant.ENCODING);
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			result = new String(content);
		}
		return parseTrain(new String(result));
	}
	
	/*
	 * 从返回的json数组中转换为List<Train>
	 */
	public static List<Train> parseTrain(String json) {
		List<Train> trains = new ArrayList<Train>();
		
		Pattern trainPattern = Pattern.compile("\\{[^}]*\\}");
		Matcher matcher = trainPattern.matcher(json);
		/*
		{
		"end_station_name":"郑州",
		"end_time":"14:22",
		"id":"5l0000D28210",
		"start_station_name":"上海虹桥",
		"start_time":"07:30",
		"value":"D282/D283"
		}
		*/
		while(matcher.find()) {
			Train train = new Train();
			String tmp = matcher.group();
			train.setNo($("id",tmp));
			train.setCode($("value",tmp));
			train.setStartStation($("start_station_name",tmp));
			train.setEndStation($("end_station_name",tmp));
			train.setStartTime($("start_time",tmp));
			train.setEndTime($("end_time",tmp));
//			System.out.println(train);
			trains.add(train);
		}
		return trains;
	}
	
	private static String $(String key,String json) {
		return ParseUtil.getValueFromJsonStr(key, json);
		/*
		Pattern p = Pattern.compile("\"" + name + "[^,}]*");
		Matcher m = p.matcher(json);
		if(m.find()) {
			String g = m.group();
			return g.replaceAll("\\s*\"\\s*", "").replaceAll(name + ":", "");
		}
		return "";
		*/
	}
}
